<?php

namespace App\Http\Controllers\Api;

use App\Models\User\WxUser;
use App\Models\User\WxUserStudentCertify;
use App\Models\WxUniversity;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class StudentController extends BaseController
{

    public function process(Request $request){
        $type = _empty_default_($request->type, '');
        if ($type == 'university_detail') {
            return $this->university_detail($request);
        }else if($type == 'university_list'){
            return $this->university_list($request);
        }
    }

    private function university_list(Request &$request){
        $keyword = _empty_default_($request->keyword, '');
        $scene = _empty_default_($request->scene, '');
        $sid = _empty_default_($request->sid, null);
        $user_id = _empty_default_($request->user_id, 0);
        if($scene == 'certify'){
            $query = WxUniversity::where('is_certify', 1);
        }else{
            $query = WxUniversity::whereNotNull('sid');
        }
        if($user_id > 0){
            $sid = WxUserStudentCertify::where('user_id', $user_id)->value('sid');
            if(_empty_($sid)){
                return $this->fail(200003, [], '查询不到该用户的学生认证信息');
            }
        }
        if($sid){
            $query = $query->where('sid', $sid);
        }

        if($keyword){
            $query = $query->where(function ($query) use ($keyword) {
                if(is_numeric($keyword)){
                    $query->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('sid', $keyword);
                }else{
                    $query->orWhere('name', 'like', '%' . $keyword . '%')->orWhere('charge', 'like', '%' . $keyword . '%')->orWhere('location', 'like', '%' . $keyword . '%');
                }
            });
        }

        $data = $query->orderBy('order', 'asc')->simplePaginate(20);
        if($data){
            $data->map(function ($v){
                $this->university_item_process($v);
                return $v;
            });
            return $this->success($data);
        }
        return $this->fail(200003);
    }


    public function university_item_process(WxUniversity &$university){

        $currentDate = Carbon::now();
        $firstTermStart = $university->sem_start_date_1 ? Carbon::parse($university->sem_start_date_1) : null;
        $firstTermEnd = $university->sem_end_date_1 ? Carbon::parse($university->sem_end_date_1) : null;
        $secondTermStart = $university->sem_start_date_2 ? Carbon::parse($university->sem_start_date_2) : null;
        $secondTermEnd = $university->sem_end_date_2 ? Carbon::parse($university->sem_end_date_2) : null;

        // 判断当前时间属于哪个学期
        if ($firstTermStart && $firstTermEnd && $currentDate->between($firstTermStart, $firstTermEnd)) {
            $university->sem_start_date = $firstTermStart->format('Y/m/d');
        } elseif ($secondTermStart && $secondTermEnd && $currentDate->between($secondTermStart, $secondTermEnd)) {
            $university->sem_start_date = $secondTermStart->format('Y/m/d');
        } else {
            $hasFirstTermData = $firstTermStart && $firstTermEnd;
            $hasSecondTermData = $secondTermStart && $secondTermEnd;

            if (!$hasFirstTermData && !$hasSecondTermData) {
                $university->sem_start_date = 'null';
            } else if ($hasFirstTermData || $hasSecondTermData) {
                $university->sem_start_date = '';
            }
        }
    }

    private function university_detail(Request &$request){
        $uname = _empty_default_($request->uname, '');
        if(_empty_($uname)){
            return $this->fail(200001);
        }
        $university = WxUniversity::where('name', $uname)->first();
        if($university){
            $this->university_item_process($university);
            return $this->success($university);
        }else{
            return $this->fail(200003);
        }
    }

    public function university(Request $request){
        $keyword = _empty_default_($request->keyword, '');
        $scene = _empty_default_($request->scene, '');
        $sid = _empty_default_($request->sid, null);
        $user_id = _empty_default_($request->user_id, 0);
        if($scene == 'certify'){
            $query = WxUniversity::where('is_certify', 1);
        }else{
            $query = WxUniversity::whereNotNull('sid');
        }
        if($user_id > 0){
            $sid = WxUserStudentCertify::where('user_id', $user_id)->value('sid');
            if(_empty_($sid)){
                return $this->fail(200003, [], '查询不到该用户的学生认证信息');
            }
        }
        if($sid){
            $query = $query->where('sid', $sid);
        }

        if($keyword){
            $query = $query->where(function ($query) use ($keyword) {
                if(is_numeric($keyword)){
                    $query->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('sid', $keyword);
                }else{
                    $query->orWhere('name', 'like', '%' . $keyword . '%')->orWhere('charge', 'like', '%' . $keyword . '%')->orWhere('location', 'like', '%' . $keyword . '%');
                }
            });
        }

        $data = $query->orderBy('order', 'asc')->simplePaginate(20);
        if($data){
            return $this->success($data);
        }
        return $this->fail(200003);
    }


    public function student_certify(Request $request){
        $way = _empty_default_($request->way, '');
        $uid = $request->uid;
        if(_empty_($way)){
            return $this->fail(200001);
        }

        $sid = _empty_default_($request->sid, '');
        $role = _empty_default_($request->role, '');
        $term = (int)(_empty_default_($request->term, ''));
        if(_empty_($sid) || _empty_($role) || _empty_($term)){
            return $this->fail(200001);
        }
        if($term < 2015){
            return $this->fail(200004, [], '仅2015届以上可认证');
        }
        if($term > 2024){
            return $this->fail(200004, [], '入学年份不合法');
        }
        if(!in_array($role, ['student'])){
            return $this->fail(200004, [], '学校身份参数不合法');
        }
        $university = WxUniversity::where('sid', $sid)->first();

        if($way == 'email'){

            if(strpos($university->email_suffix, '@') !== 0){
                return $this->fail(200003, [], '该学校还没有正确的邮箱后缀');
            }

            $code = _empty_default_($request->code, '');
            $email = _empty_default_($request->email, '');

            if(_empty_($code) || _empty_($email)){
                return $this->fail(200001);
            }

            if(_empty_($university->email_suffix)){
                return $this->fail(200003, [], '该学校不允许邮箱认证');
            }
            if(!StrUtils::endsWith($email, $university->email_suffix)){
                return $this->fail(200004, [], '邮箱后缀和学校邮箱不匹配');
            }
            $cache_key = md5($uid.':code:60:'.$email);
            if(!Cache::has($cache_key)){
                return $this->fail(200044);
            }
            if(Cache::get($cache_key) != $code){
                return $this->fail(200004, [], '验证码错误');
            }
            $cetify = WxUserStudentCertify::where('user_id', $uid)->first();
            if($cetify){
                if($cetify->status == 1){
                    return $this->fail(200010, [], '您已经完成学生认证，无需再次认证');
                }else{
                    DB::beginTransaction();
                    try {
                        // todo:
                        $cetify->status = 1;
                        $cetify->save();
                        WxUser::where('id', $uid)->update(['university' => $university->name]);
                        Cache::forget('get:cached:user:'.$uid);
                        DB::commit();
                        return $this->success($cetify);
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                        return $this->fail(200002);
                    }
                }
            }
            DB::beginTransaction();
            try {
                $cetify = new WxUserStudentCertify();
                $cetify->user_id = $uid;
                $cetify->sid = $university->sid;
                $cetify->school = $university->name;
                $cetify->role = $role;
                $cetify->term = $term;
                $cetify->email = $email;
                $cetify->status = 1;
                $r = $cetify->save();
                if($r){
                    WxUser::where('id', $uid)->update(['university' => $university->name]);
                    Cache::forget('get:cached:user:'.$uid);
                    DB::commit();
                    return $this->success($cetify);
                }else{
                    DB::rollBack();
                    return $this->fail(200002);
                }
            } catch (\Exception $e) {
                DB::rollBack();
                _logger_(__file__, __line__, $e->getMessage());
                return $this->fail(200002);
            }
        }else if($way == 'school-card'){
            $picture = _empty_default_($request->picture, '');
            $picture2 = _empty_default_($request->picture2, '');
            $introduce = _empty_default_($request->introduce, '');
            if(_empty_($picture)){
                return $this->fail(200001, [], '至少上传一张图片');
            }
            $cetify = WxUserStudentCertify::where('user_id', $uid)->first();
            if($cetify) {
                if ($cetify->status == 1) {
                    return $this->fail(200010, [], '您已经完成学生认证，无需再次认证');
                }else{
//                    return $this->fail(200010, [], '您的申请正在审核中，无需重复提交');
                }
            }

            $img_state_change = [];
            if($picture){
                $img_state_change[] = $picture;
            }
            if($picture2){
                $img_state_change[] = $picture2;
            }
            DB::beginTransaction();
            try {
                if($cetify){

                }else{
                    $cetify = new WxUserStudentCertify();
                }
                $cetify->user_id = $uid;
                $cetify->sid = $university->sid;
                $cetify->school = $university->name;
                $cetify->role = $role;
                $cetify->term = $term;

                $cetify->picture = $picture;
                $cetify->picture2 = $picture2;
                $cetify->introduce = $introduce;

                $cetify->status = 0;
                $r = $cetify->save();
                if($r){
                    Utils::image_state_change($img_state_change, 1);
                    UserUtils::assistant_notice_review(108, $cetify->user_id);
                    DB::commit();
                    return $this->success([], 200, '已提交审核');
                }else{
                    DB::rollBack();
                    return $this->fail(200002);
                }
            } catch (\Exception $e) {
                DB::rollBack();
                _logger_(__file__, __line__, $e->getMessage());
                return $this->fail(200002);
            }
        }
    }
//    [
//                "name"=> "思想政治实践课2",
//                "num"=> "U1300008",
//                "credit"=> "1.0",
//                "totalHours"=> "16.0",
//                "lectureHours"=> "0.0",
//                "computeHours"=> "0.0",
//                "category"=> "专业主干课/必修课",
//                "teachMethod"=> "讲授",
//                "method"=> "非统考",
//                "teacher"=> "黄鹏振",
//                "weeks"=> [
//                    3,
//                    5,
//                    7,
//                    9,
//                    11,
//                    13,
//                    15,
//                    17
//                ],
//                "section"=> 11,
//                "address"=> "线上上课（北1）",
//                "rawWeeks"=> "2-17",
//                "rawSection"=> "五[11-12节]单",
//                "week"=> 5,
//                "sectionCount"=> 2
//            ]
}


